import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String networkStateText;
  static const EventChannel _eventChannelPlugin = EventChannel('my.flutter.event/network');//定义接收底层操作系统主动发来的消息通道
  StreamSubscription _streamSubscription;//广播流来处理EventChannel发来的消息
  @override
  void initState() {
    super.initState();
    _streamSubscription=_eventChannelPlugin
        .receiveBroadcastStream()
        .listen(_onToDart, onError: _onToDartError);//注册消息回调函数
  }
  void _onToDart(dynamic message) {//底层发送成功消息时会进入到这个函数来接收
    switch(message['code']){
      case "80001"://如果是网络可用
        print("网络可用");
          networkStateText="enable";
          setState(() {
        });
        break;
    }
  }
  void _onToDartError(dynamic error) {//底层发送错误消息时会进入到这个函数来接收
    switch(error.code){
      case "90001"://如果网络不可用
        print("网络不可用");
        setState(() {
          networkStateText="disable";
        });
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Text('Network:$networkStateText'),
        ),
      ),
    );
  }
}
